package cmd

import (
	"fmt"
	"github.com/sirupsen/logrus"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
	cfg "order/pkg/config"
	"order/pkg/log"
	"os"
	"strings"
)

var cfgFile string
var config = cfg.DefaultConfig()

// dkronCmd represents the dkron command
var orderCmd = &cobra.Command{
	Use:   "orderhook",
	Short: "order hook embeded in shared-kubernetes",
	Long:  "order hook embeded in shared-kubernetes, try to resync k8s pod & pv update info to MQ",
}

func Execute() {
	if err := orderCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}

func init() {
	cobra.OnInitialize(initConfig)
	orderCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file path")
}

// initConfig reads in config file and ENV variables if set.
func initConfig() {
	if cfgFile != "" {
		// Use config file from the flag.
		viper.SetConfigFile(cfgFile)
	} else {
		viper.SetConfigName("orderhook")        // name of config file (without extension)
		viper.AddConfigPath("/etc/orderhook")   // call multiple times to add many search paths
		viper.AddConfigPath("$HOME/.orderhook") // call multiple times to add many search paths
		viper.AddConfigPath("./config")         // call multiple times to add many search paths
	}

	viper.SetEnvPrefix("orderhook")
	replacer := strings.NewReplacer("-", "_")
	viper.SetEnvKeyReplacer(replacer)
	viper.AutomaticEnv() // read in environment variables that match

	err := viper.ReadInConfig() // Find and read the config file
	if err != nil {             // Handle errors reading the config file
		logrus.WithError(err).Info("No valid config found: Applying default values.")
	}

	if err := viper.Unmarshal(config); err != nil {
		logrus.WithError(err).Fatal("config: Error unmarshalling config")
	}
	log.InitLogger(viper.GetString("log-level"), config.NodeName)
}
